/**
 * Copyright 2021 Huawei Technologies Co., Ltd
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mindspore.classificationforcar.widget;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.mindspore.classificationforcar.R;
import com.mindspore.classificationforcar.gallery.classify.TrackingMobile;

import java.io.File;

/**
 * The main interface of camera preview.
 * Using Camera 2 API.
 */
public class CameraActivity extends AppCompatActivity {
    private static final String TAG = "CameraActivity";

    private String filePath;
    private TrackingMobile trackingMobile;

    private TextView resultText;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate");
        setContentView(R.layout.activity_camera);

        filePath =getIntent().getStringExtra("FILEPATH");
        resultText = findViewById(R.id.textResult);
        trackingMobile = new TrackingMobile(this);
        boolean ret = trackingMobile.loadModelFromBuf(filePath);
        if (!ret) {
            Log.e(TAG, "Load model error.");
            return;
        }
        addCameraFragment();
    }

    protected void addCameraFragment() {
        CameraFragment cameraFragment = CameraFragment.newInstance(bitmap -> {
            runOnUiThread(() -> initMindspore(bitmap));
        });

        getSupportFragmentManager().beginTransaction()
                .replace(R.id.container, cameraFragment)
                .commitAllowingStateLoss();
    }


    private void initMindspore(Bitmap bitmap) {
        // run net.
        long startTime = System.currentTimeMillis();
        String result = trackingMobile.MindSpore_runnet(bitmap);
        long endTime = System.currentTimeMillis();
        resultText.setText(TextUtils.isEmpty(result)?"正在识别...":result);
        Log.d(TAG, "RUNNET CONSUMING：" + (endTime - startTime) + "ms");
        Log.d(TAG, "result：" + result);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        trackingMobile.unloadModel();
    }
}
